package cc.telecomdigital.tdstock;

import java.util.TimerTask;

import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

/** 
#  *  
#  * decrease alpha channel value from 255 to 0. 
#  * 
#  */
public class ColorRefreshTask extends TimerTask
{
	private RefreshHandlerInterface	refreshHandler;
	private final static int			DELAY_ONCE	= 200;
	private final static int			TOTAL_RUNTIME	= 1500;
	private final static int			POWER_16_16	= 16 * 16 * 16 * 16 * 16
													* 16;
	private final static int			INCREASE_ONCE	= 0xff / (TOTAL_RUNTIME / DELAY_ONCE);
	private int					color;
	private Object					id;
	private int					startTime;
	private int					alphaChannel;

	/**
	 * 
	 * @param color ( current background color)
	 * @param id  (the id of the refreshing object)
	 */
	public ColorRefreshTask(RefreshHandlerInterface refreshHandler, int color,
			Object id)
	{
		super();
		TDStockLog.d("color", "ready to set color!");
		this.color = color;
		this.id = id;
		this.startTime = 0;
		this.alphaChannel = 0;
		this.refreshHandler = refreshHandler;
	}

	public void setRefreshObj(Object id)
	{
		this.id = id;
	}

	public void run()
	{

		int colorComm = color - 0xff000000; //RGB color value;
		int currColor = 0;

		if (startTime < TOTAL_RUNTIME)
		{
			startTime += DELAY_ONCE;
			alphaChannel += INCREASE_ONCE;
			currColor = POWER_16_16 * alphaChannel + colorComm;
			//TDStockLog.d("color", Integer.toHexString(currColor));
			sendMsg(currColor);
			if (refreshHandler == null
					|| refreshHandler.getHandler() == null
					|| Thread.interrupted())
			{
				cancel();
				return;
			}

			refreshHandler.getHandler().postDelayed(this, DELAY_ONCE);

		}
		else
		{
			sendMsg(currColor <= color ? color : 0);
			cancel();
		}

	}

	public void startTimer()
	{
		if (refreshHandler == null || refreshHandler.getHandler() == null
				|| Thread.interrupted())
		{
			return;
		}
		refreshHandler.getHandler().postDelayed(this, DELAY_ONCE);
	}

	private void sendMsg(final int currColor)
	{
		//		Message message = _messageHandler.obtainMessage(); 
		//		message.what = MESSAGE_HANDLE_ID_UPDATE_BACKGROUND;
		//		Bundle bundle = new Bundle();
		//		bundle.putInt(MESSAGE_KEY_ID, id);
		//		bundle.putInt(MESSAGE_KEY_COLOR, currColor);
		//		message.setData(bundle);
		//		_messageHandler.sendMessage(message);

		final Runnable myUpdateResults = new Runnable()
		{
			public void run()
			{
				if (refreshHandler == null
						|| refreshHandler.getHandler() == null
						|| Thread.interrupted())
				{
					return;
				}
				refreshHandler.updateBackground(id, currColor);
			}
		};

		new Thread()
		{
			public void run()
			{
				if (refreshHandler == null
						|| refreshHandler.getHandler() == null
						|| Thread.interrupted())
				{
					return;
				}
				refreshHandler.getHandler().post(myUpdateResults);
			}
		}.start();

	}

	public void stopTimer()
	{
		this.cancel();
	}

}
